import pyflag.FlagFramework as FlagFramework
import pyflag.conf
config=pyflag.conf.ConfObject()
import pyflag.FileSystem as FileSystem
import pyflag.Reports as Reports
import pyflag.DB as DB
from pyflag.Scanner import *
import pyflag.Scanner as Scanner
from pyflag.ColumnTypes import StringType, InodeIDType, ColumnType, FilenameType, IntegerType, TimestampType
import pyflag.Reports as Reports
import os.path


class PathType(ColumnType):
    def __init__(self, **kwargs):
        ColumnType.__init__(self, name="Path", column='path', **kwargs)

    def create(self):
        return "`%s` text default '' " % self.column


class FoundLogsCaseTable(FlagFramework.CaseTable):
   
    """ Found logs files table """
    primary= "inode_id"
    name = 'foundlogs'
    columns = [ [ InodeIDType, {} ],
                [StringType,{"name":"Log Type","column":"logtype"}],
                [ PathType,{}]
                ]

class LogFinder(Reports.report):
    """ Finds HTTP server Files """
    name = "Show Found Logs"
    family = "Log Finder"
    description="This report will give a table with files which are Apache Logs"

    def form(self,query,result):
        result.case_selector()
        
    def display(self,query,result):
        dbh=self.DBO(query['case'])
        try:
            result.table(
                elements = [ 
                             FilenameType(case=query['case']),
                             StringType('Type','logtype'),
                             IntegerType('Size','size', table='inode'),
                             TimestampType(name='Timestamp',column='mtime', table='inode')
                             ],
                table = 'foundlogs',
                case = query['case']
                )
        except DB.DBError,e:
            result.para("Error reading the Type table.")
            result.para("Error reported was:")
            result.text(e,style="red")


class LogsScan(GenScanFactory):
    """ Scan filesystem for logs """
    default = True
    depends = ['TypeScan']
    group = "LogFinders"
    order=400

    class Drawer(Scanner.Drawer):
        description = "Log Finders"
        name = "Log finders"
        group = "LogFinders"
        default = True
        
    
    
    class Scan(ScanIfType):
        types=('text/plain; charset=us-ascii' ,
               'protocol/x-http-request' , )
        
        def boring(self, metadata, data=''):
            #print "Boring invoked \n\n\n\n\n\n\n\n\n"
            return True
        
        def process(self, data,metadata=None):
            dbh=DB.DBO(self.case)


        def finish(self):
            dbh=DB.DBO(self.case)

            dbh.execute("select inode_id from type where inode_id=" + str(self.inode_id) + " and \
                                (mime like 'text/plain; charset=us-ascii' or mime like 'protocol/x-http-request' )")
            dbresult= dbh.fetch()

            if dbresult:
                print self.fd.fd.name + "\n\n\n\n\n\n"
                fd= open(os.path.abspath(self.fd.fd.name),'r')
                marker=[]
                marker.append(True);
                marker.append(True);
                
                for i in range(1,20):
                    line=fd.readline()
                    if line:
                        # Apache Log " 127.0.0.1 - frank [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326"
                        if re.match("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3} - [\w.+|-] \[\d\d/\w{3}/\d\d\d\d:\d\d:\d\d:\d\d [+|-]\d{4}] \".+ HTTP/1..\"", line):
                            print line
                            marker[1]=False
                        #IIS log: "192.168.114.201, -, 03/20/01, 7:55:20, W3SVC2, SERVER, 172.21.13.45, 4502, 163, 3223, 200, 0, GET, /DeptLogo.gif, -,"
                        elif re.match("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3},\s?-|\w+,\s?\d\d/\d\d/\d\d,\s?\d{1,2},\s?\w+,\s?\w+,\s?\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3},\s?\d+,\s?\d+,\s?\d+,\s?\w+,.+,.+", line):
                            print line
                            marker[0]=False
                         
                        else:
                            marker[0]=False
                            marker[1]=False

                if marker[0]:
                   sqlcomm="insert into foundlogs(inode_id, logtype, path) values ( %d, '%s', '%s' )" %(self.inode_id, "Apache Access Log", "File")
                   #print sqlcomm
                   dbh.execute(sqlcomm)
                elif marker[1]:
                   sqlcomm="insert into foundlogs(inode_id, logtype, path) values ( %d, '%s', '%s' )" %(self.inode_id, "IIS Access Log", "File")
                   #print sqlcomm
                   dbh.execute(sqlcomm) 
                
